import pymysql as sql
import schedule
import time
from datetime import datetime
from api.zabbix_api import get_hosts_simple
from feishu.feishu_webhook import FeiShuWebhook
import hashlib
import json


class ZabbixAlertMonitor:
    def __init__(self):
        """初始化监控器"""
        # 数据库连接配置
        self.db_config = {
            'host': '10.104.14.27',
            'user': 'zabbix', 
            'password': 'Chery@zabbix_pwd',
            'database': 'zabbix'
        }
        
        # 飞书webhook配置
        self.webhook = FeiShuWebhook("https://open.feishu.cn/open-apis/bot/v2/hook/81852277-30cb-47a9-92be-b39543345b0e")
        
        # 用于存储已通知的告警，避免重复通知
        self.notified_alerts = set()
        
        # 定期通知配置
        self.last_full_notification_time = None
        self.notification_interval = 30  # 每30分钟发送一次完整状态更新
        
        # 连接数据库
        self.db_connection = None
        self.init_db_connection()
    
    def init_db_connection(self):
        """初始化数据库连接"""
        try:
            self.db_connection = sql.connect(**self.db_config)
            print("数据库连接成功")
        except Exception as e:
            print(f"数据库连接失败: {e}")
    
    def get_trigger_dependencies(self):
        """获取触发器依赖关系映射"""
        try:
            cursor = self.db_connection.cursor()
            query = """
            SELECT 
                td.triggerid_down,
                td.triggerid_up,
                t_down.description as downstream_trigger,
                t_up.description as upstream_trigger,
                h_down.host as downstream_host,
                h_up.host as upstream_host
            FROM trigger_depends td
            INNER JOIN triggers t_down ON td.triggerid_down = t_down.triggerid
            INNER JOIN triggers t_up ON td.triggerid_up = t_up.triggerid
            INNER JOIN functions f_down ON t_down.triggerid = f_down.triggerid
            INNER JOIN items i_down ON f_down.itemid = i_down.itemid
            INNER JOIN hosts h_down ON i_down.hostid = h_down.hostid
            INNER JOIN functions f_up ON t_up.triggerid = f_up.triggerid
            INNER JOIN items i_up ON f_up.itemid = i_up.itemid
            INNER JOIN hosts h_up ON i_up.hostid = h_up.hostid
            """
            
            cursor.execute(query)
            results = cursor.fetchall()
            
            # 构建依赖关系映射
            # key: 下游触发器ID, value: 上游触发器信息
            downstream_to_upstream = {}  # 下游 -> 上游
            upstream_to_downstream = {}  # 上游 -> 下游
            
            for row in results:
                triggerid_down, triggerid_up, downstream_trigger, upstream_trigger, downstream_host, upstream_host = row
                
                # 构建下游到上游的映射
                if triggerid_down not in downstream_to_upstream:
                    downstream_to_upstream[triggerid_down] = {
                        'downstream_trigger': downstream_trigger,
                        'downstream_host': downstream_host,
                        'upstream_triggers': [],
                        'upstream_hosts': [],
                        'upstream_triggerids': []
                    }
                
                downstream_to_upstream[triggerid_down]['upstream_triggers'].append(upstream_trigger)
                downstream_to_upstream[triggerid_down]['upstream_hosts'].append(upstream_host)
                downstream_to_upstream[triggerid_down]['upstream_triggerids'].append(triggerid_up)
                
                # 构建上游到下游的映射（用于快速查找）
                if triggerid_up not in upstream_to_downstream:
                    upstream_to_downstream[triggerid_up] = {
                        'upstream_trigger': upstream_trigger,
                        'upstream_host': upstream_host,
                        'downstream_triggers': [],
                        'downstream_hosts': [],
                        'downstream_triggerids': []
                    }
                
                upstream_to_downstream[triggerid_up]['downstream_triggers'].append(downstream_trigger)
                upstream_to_downstream[triggerid_up]['downstream_hosts'].append(downstream_host)
                upstream_to_downstream[triggerid_up]['downstream_triggerids'].append(triggerid_down)
            
            return {
                'downstream_to_upstream': downstream_to_upstream,
                'upstream_to_downstream': upstream_to_downstream
            }
            
        except Exception as e:
            print(f"获取触发器依赖关系失败: {e}")
            return {'downstream_to_upstream': {}, 'upstream_to_downstream': {}}

    def check_upstream_problems(self, trigger_ids, parent_host_ids):
        """检查上游依赖触发器是否处于问题状态"""
        try:
            cursor = self.db_connection.cursor()
            placeholders = ','.join(['%s'] * len(trigger_ids))
            
            query = f"""
            SELECT DISTINCT p.objectid, h.hostid, h.host, p.name
            FROM problem p
            INNER JOIN triggers t ON p.objectid = t.triggerid
            INNER JOIN functions f ON t.triggerid = f.triggerid
            INNER JOIN items i ON f.itemid = i.itemid
            INNER JOIN hosts h ON i.hostid = h.hostid
            WHERE p.r_eventid IS NULL 
                AND p.source = 0 
                AND p.object = 0
                AND p.objectid IN ({placeholders})
            """
            
            cursor.execute(query, trigger_ids)
            upstream_problems = cursor.fetchall()
            
            # 返回有问题的上游触发器对应的主机
            problem_upstream_hosts = set()
            for row in upstream_problems:
                triggerid, hostid, hostname, problem_name = row
                problem_upstream_hosts.add(hostid)
            
            return problem_upstream_hosts
            
        except Exception as e:
            print(f"检查上游问题状态失败: {e}")
            return set()

    def get_current_alerts(self):
        """获取当前所有告警（过滤下游触发器的级联告警，保留上游触发器告警）"""
        try:
            self.init_db_connection()
            cursor = self.db_connection.cursor()
            
            # 首先获取所有告警 - 按触发器级别返回，不合并相同主机的多个触发器
            query = """
            SELECT 
                h.hostid, 
                h.host, 
                h.name as hostname,
                p.objectid as trigger_id,
                t.description as trigger_description,
                p.name as problem_name,
                p.severity as problem_severity,
                COUNT(DISTINCT p.eventid) as problem_count, 
                COUNT(DISTINCT a.alertid) as alert_count, 
                GROUP_CONCAT(DISTINCT concat(ht.tag, ":", ht.value) SEPARATOR ', ') as tags,
                GROUP_CONCAT(DISTINCT hg.groupid SEPARATOR ', ') as group_ids,
                GROUP_CONCAT(DISTINCT g.name SEPARATOR ', ') as host_groups
            FROM problem p
            INNER JOIN triggers t ON p.objectid = t.triggerid
            INNER JOIN functions f ON t.triggerid = f.triggerid
            INNER JOIN items i ON f.itemid = i.itemid
            INNER JOIN hosts h ON i.hostid = h.hostid
            LEFT JOIN host_tag ht ON i.hostid = ht.hostid
            LEFT JOIN hosts_groups hg ON h.hostid = hg.hostid
            LEFT JOIN hstgrp g ON hg.groupid = g.groupid
            LEFT JOIN events e ON p.eventid = e.eventid
            LEFT JOIN alerts a ON e.eventid = a.eventid
            WHERE p.r_eventid IS NULL 
                AND p.source = 0 
                AND p.object = 0
                AND g.name in ("Applications", "AP办公网段", "AP生产网段", "生产交换机网段", "办公交换机网段", "重要业务网段", "监控交换机网段")
            GROUP BY h.hostid, h.host, h.name, p.objectid, t.description, p.name, p.severity
            ORDER BY p.severity DESC, h.host, p.severity DESC;
            """
            
            cursor.execute(query)
            all_alerts = cursor.fetchall()
            
            # 获取触发器依赖关系
            dependency_data = self.get_trigger_dependencies()
            downstream_to_upstream = dependency_data.get('downstream_to_upstream', {})
            upstream_to_downstream = dependency_data.get('upstream_to_downstream', {})
            
            # 过滤结果
            filtered_alerts = []
            skipped_downstream_alerts = []  # 记录被跳过的下游告警
            
            for alert in all_alerts:
                host_id, host_ip, hostname, trigger_id, trigger_description, problem_name, problem_severity, problem_count, alert_count, tags, group_ids, host_groups = alert
                
                # 检查当前触发器是否是下游触发器（有依赖关系的触发器）
                if trigger_id in downstream_to_upstream:
                    # 检查是否需要跳过此下游触发器
                    dependency_info = downstream_to_upstream[trigger_id]
                    upstream_trigger_ids = dependency_info['upstream_triggerids']
                    
                    # 检查上游触发器是否处于问题状态
                    problem_upstream_hosts = self.check_upstream_problems(upstream_trigger_ids, [])
                    
                    if problem_upstream_hosts:
                        # 跳过此下游告警，保留上游告警
                        skipped_downstream_alerts.append({
                            'host': hostname,
                            'ip': host_ip,
                            'trigger': trigger_description,
                            'problem': problem_name,
                            'upstream_hosts': dependency_info['upstream_hosts']
                        })
                        print(f"跳过主机 {hostname}({host_ip}) 触发器 '{trigger_description}' 的下游告警（上游触发器有问题）")
                        continue
                
                # 如果不是需要跳过的下游触发器，则保留此告警
                # 构建每个触发器的告警信息，包括依赖关系信息
                alert_with_dependencies = {
                    'host_id': host_id,
                    'host_ip': host_ip,
                    'hostname': hostname,
                    'trigger_id': trigger_id,
                    'trigger_description': trigger_description,
                    'problem_name': problem_name,
                    'problem_severity': problem_severity,
                    'problem_count': problem_count,
                    'alert_count': alert_count,
                    'tags': tags,
                    'group_ids': group_ids,
                    'host_groups': host_groups,
                    'dependencies': {}
                }
                
                # 添加依赖关系信息
                if trigger_id in downstream_to_upstream:
                    dependency_info = downstream_to_upstream[trigger_id]
                    alert_with_dependencies['dependencies'] = {
                        'is_downstream': True,
                        'upstream_triggers': dependency_info['upstream_triggers'],
                        'upstream_hosts': dependency_info['upstream_hosts'],
                        'upstream_triggerids': dependency_info['upstream_triggerids']
                    }
                elif trigger_id in upstream_to_downstream:
                    dependency_info = upstream_to_downstream[trigger_id]
                    alert_with_dependencies['dependencies'] = {
                        'is_upstream': True,
                        'downstream_triggers': dependency_info['downstream_triggers'],
                        'downstream_hosts': dependency_info['downstream_hosts'],
                        'downstream_triggerids': dependency_info['downstream_triggerids']
                    }
                
                filtered_alerts.append(alert_with_dependencies)
            
            # 输出过滤统计信息
            print(f"原始触发器告警数量: {len(all_alerts)}")
            print(f"过滤后触发器告警数量: {len(filtered_alerts)}")
            print(f"跳过的下游触发器告警: {len(skipped_downstream_alerts)}")
            
            if skipped_downstream_alerts:
                print("被跳过的下游触发器告警详情:")
                for skipped in skipped_downstream_alerts:
                    print(f"  - 主机: {skipped['host']}({skipped['ip']}) 触发器: '{skipped['trigger']}' 问题: {skipped['problem']}")
                    print(f"    上游问题主机: {', '.join(skipped['upstream_hosts'])}")
            
            return filtered_alerts
            
        except Exception as e:
            print(f"获取告警数据失败: {e}")
            return []
    
    def get_host_tags_info(self, host_ip):
        """获取主机的标签信息"""
        try:
            host_info = get_hosts_simple(host_ip)
            if not host_info or len(host_info) == 0:
                return None
            
            host_data = host_info[0]
            tags = host_data.get('tags', [])
            
            # 提取设备名称和类型信息
            device_name = host_data.get('name', host_ip)  # 默认使用hostname，如果没有则使用IP
            type_tag = None
            position_tag = None
            
            for tag in tags:
                if tag.get('tag') == '类型':
                    type_tag = tag.get('value')
                elif tag.get('tag') == '位置':
                    position_tag = tag.get('value')
            
            return {
                'device_name': device_name,
                'type': type_tag,
                'position': position_tag,
                'tags': tags
            }
            
        except Exception as e:
            print(f"获取主机 {host_ip} 标签信息失败: {e}")
            return None
    
    def classify_alerts_by_type(self, alerts):
        """按类型分类告警 - 每个触发器作为独立项目"""
        classified_alerts = {}
        
        for alert in alerts:
            # alert 现在是一个字典，包含触发器级别的信息
            host_ip = alert['host_ip']
            hostname = alert['hostname']
            trigger_description = alert['trigger_description']
            problem_name = alert['problem_name']
            problem_severity = alert['problem_severity']
            problem_count = alert['problem_count']
            alert_count = alert['alert_count']
            tags = alert['tags']
            group_ids = alert['group_ids']
            host_groups = alert['host_groups']
            dependencies = alert['dependencies']
            
            # 获取主机详细信息
            host_info = self.get_host_tags_info(host_ip)
            if not host_info:
                continue
            
            device_type = host_info['type'] or '未分类设备'
            device_name = host_info['device_name']
            position = host_info['position']
            
            # 创建分类键
            category_key = device_type
            
            # 构建触发器信息（包括依赖关系）
            trigger_display_info = {
                'ip': host_ip,
                'hostname': hostname,
                'device_name': device_name,
                'position': position,
                'trigger_description': trigger_description,
                'problem_name': problem_name,
                'problem_severity': problem_severity,
                'problem_count': problem_count,
                'alert_count': alert_count,
                'tags': tags,
                'group_ids': group_ids,
                'host_groups': host_groups,
                'dependencies': dependencies
            }
            
            # 添加到对应分类
            if category_key not in classified_alerts:
                classified_alerts[category_key] = []
            classified_alerts[category_key].append(trigger_display_info)
        
        return classified_alerts
    
    def generate_alert_hash(self, host_ip, problems):
        """生成告警唯一标识，用于去重"""
        content = f"{host_ip}:{problems}"
        return hashlib.md5(content.encode('utf-8')).hexdigest()
    
    def check_new_alerts(self):
        """检查是否有新告警或状态变化"""
        try:
            alerts = self.get_current_alerts()
            print(f"获取到 {len(alerts)} 个触发器告警")
            
            # 获取当前告警的详细哈希
            current_alerts_dict = {}
            for alert in alerts:
                # alert 现在是一个字典
                host_ip = alert['host_ip']
                trigger_description = alert['trigger_description']
                problem_name = alert['problem_name']
                problem_severity = alert['problem_severity']
                problem_count = alert['problem_count']
                alert_count = alert['alert_count']
                
                alert_hash = self.generate_trigger_alert_hash(
                    host_ip, trigger_description, problem_name, problem_severity, problem_count
                )
                current_alerts_dict[alert_hash] = {
                    'alert': alert,
                    'host_ip': host_ip,
                    'trigger_description': trigger_description,
                    'problem_name': problem_name,
                    'problem_severity': problem_severity,
                    'problem_count': problem_count
                }
            
            current_alert_hashes = set(current_alerts_dict.keys())
            
            # 分析告警变化
            new_alerts = current_alert_hashes - self.notified_alerts  # 新增告警
            resolved_alerts = self.notified_alerts - current_alert_hashes  # 已解决告警
            changed_alerts = self.detect_trigger_alert_changes(current_alerts_dict)  # 状态变化的告警
            
            # 检查是否需要定期发送完整状态更新
            current_time = datetime.now()
            need_periodic_notification = False
            if self.last_full_notification_time is None:
                need_periodic_notification = True
            else:
                time_diff = (current_time - self.last_full_notification_time).total_seconds() / 60
                if time_diff >= self.notification_interval:
                    need_periodic_notification = True
            
            # 如果有告警变化或需要定期通知，发送通知
            if new_alerts or resolved_alerts or changed_alerts or need_periodic_notification:
                if need_periodic_notification and not (new_alerts or resolved_alerts or changed_alerts):
                    print(f"[{datetime.now()}] 定期状态更新")
                else:
                    print(f"[{datetime.now()}] 检测到告警变化:")
                    print(f"  - 新增告警: {len(new_alerts)} 个")
                    print(f"  - 已解决: {len(resolved_alerts)} 个") 
                    print(f"  - 状态变化: {len(changed_alerts)} 个")
                
                alert_changes = {
                    'new_alerts': new_alerts,
                    'resolved_alerts': resolved_alerts,
                    'changed_alerts': changed_alerts,
                    'periodic_notification': need_periodic_notification
                }
                
                self.process_and_notify_alerts(alerts, alert_changes)
                
                # 更新已通知的告警集合和时间
                self.notified_alerts = current_alert_hashes
                if need_periodic_notification:
                    self.last_full_notification_time = current_time
            else:
                print(f"[{datetime.now()}] 没有告警变化，跳过通知")
                
        except Exception as e:
            print(f"检查告警时出错: {e}")
    
    def generate_detailed_alert_hash(self, host_ip, problems, problem_count, max_severity):
        """生成详细的告警唯一标识，包含更多状态信息（保留以兼容旧代码）"""
        content = f"{host_ip}:{problems}:{problem_count}:{max_severity}"
        return hashlib.md5(content.encode('utf-8')).hexdigest()
    
    def generate_trigger_alert_hash(self, host_ip, trigger_description, problem_name, problem_severity, problem_count):
        """为触发器级别告警生成唯一标识"""
        content = f"{host_ip}:{trigger_description}:{problem_name}:{problem_severity}:{problem_count}"
        return hashlib.md5(content.encode('utf-8')).hexdigest()
    
    def detect_alert_changes(self, current_alerts_dict):
        """检测告警状态变化（保留以兼容旧代码）"""
        return self.detect_trigger_alert_changes(current_alerts_dict)
    
    def detect_trigger_alert_changes(self, current_alerts_dict):
        """检测触发器级别告警状态变化"""
        changed_alerts = []
        
        # 检查已存在的告警是否有状态变化
        for alert_hash in self.notified_alerts:
            if alert_hash in current_alerts_dict:
                # 告警仍然存在，检查是否有状态变化
                current_info = current_alerts_dict[alert_hash]
                # 这里可以添加更多状态检查逻辑
                # 比如问题数量变化、严重程度变化等
                # 目前简单的实现，可以扩展
                changed_alerts.append(alert_hash)
                
        return changed_alerts
    
    def format_feishu_message(self, classified_alerts, alert_changes=None):
        """格式化飞书消息"""
        # 过滤掉未分类设备
        filtered_alerts = {k: v for k, v in classified_alerts.items() if k != '未分类设备'}
        
        if not filtered_alerts:
            return "🎉 当前没有活跃告警，系统运行正常！"
        
        # 构建消息头部
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        message = f"🚨 **Zabbix告警监控报告**\n\n"
        message += f"📅 **检查时间**: {current_time}\n"
        message += f"📊 **告警类别**: {len(filtered_alerts)} 类\n"
        
        # 统计总主机数和问题总数
        total_hosts = sum(len(hosts) for hosts in filtered_alerts.values())
        total_problems = sum(sum(host['problem_count'] for host in hosts) for hosts in filtered_alerts.values())
        message += f"🏠 **受影响主机**: {total_hosts} 台\n"
        message += f"🔍 **问题总数**: {total_problems} 个\n\n"
        
        # 如果有告警变化信息，添加变化摘要
        if alert_changes:
            has_changes = (alert_changes.get('new_alerts') or alert_changes.get('resolved_alerts') or alert_changes.get('changed_alerts'))
            is_periodic = alert_changes.get('periodic_notification', False)
            
            if has_changes or is_periodic:
                message += "## 🔄 "
                if is_periodic and not has_changes:
                    message += "定期状态更新\n\n"
                    message += "📝 **这是定期状态更新，暂无告警变化**\n\n"
                else:
                    message += "告警变化摘要\n\n"
                
                if alert_changes.get('new_alerts'):
                    message += f"🆕 **新增告警**: {len(alert_changes['new_alerts'])} 个\n"
                if alert_changes.get('resolved_alerts'):
                    message += f"✅ **已解决**: {len(alert_changes['resolved_alerts'])} 个\n"
                if alert_changes.get('changed_alerts'):
                    message += f"🔀 **状态变化**: {len(alert_changes['changed_alerts'])} 个\n"
                
                message += "\n"
        
        # 按类型分组显示告警 - 显示触发器级别的详细信息和依赖关系
        message += "## 📋 触发器告警详情\n\n"
        
        for device_type, triggers in filtered_alerts.items():
            # 判断是否为生产网相关设备类型
            production_keywords = ['生产', 'prod', '生产网', '核心', '业务']
            is_production = any(keyword.lower() in device_type.lower() for keyword in production_keywords)
            
            # 根据类型选择圆点颜色
            if is_production:
                message += f"🔴 {device_type}\n"
            else:
                message += f"🟡 {device_type}\n"
            
            # 按主机分组显示触发器
            host_triggers = {}
            for trigger in triggers:
                host_key = f"{trigger['ip']} ({trigger['device_name']})"
                if host_key not in host_triggers:
                    host_triggers[host_key] = []
                host_triggers[host_key].append(trigger)
            
            # 显示每个主机的触发器
            for host_display, host_trigger_list in host_triggers.items():
                message += f"\n**{host_display}**\n"
                
                for trigger in host_trigger_list:
                    # 处理触发器标签
                    trigger_tags = []
                    if trigger['position']:
                        trigger_tags.append(f"位置:{trigger['position']}")
                    
                    # 如果没有标签，显示"无"
                    tag_display = "; ".join(trigger_tags) if trigger_tags else "无"
                    
                    # 获取严重程度emoji
                    severity_emoji = self.get_severity_emoji(trigger['problem_severity'])
                    
                    # 显示触发器和问题信息
                    message += f"{severity_emoji} **{trigger['trigger_description']}**: {trigger['problem_name']} (位置: {tag_display})\n"
                    
                    # 显示依赖关系信息
                    dependencies = trigger['dependencies']
                    if dependencies:
                        if dependencies.get('is_downstream', False):
                            # 显示上游依赖
                            upstream_triggers = dependencies.get('upstream_triggers', [])
                            upstream_hosts = dependencies.get('upstream_hosts', [])
                            if upstream_triggers:
                                message += f"  📍 **依赖上游触发器**: {', '.join(upstream_triggers)}\n"
                            if upstream_hosts:
                                message += f"  🔗 **上游主机**: {', '.join(upstream_hosts)}\n"
                                
                        elif dependencies.get('is_upstream', False):
                            # 显示下游依赖
                            downstream_triggers = dependencies.get('downstream_triggers', [])
                            downstream_hosts = dependencies.get('downstream_hosts', [])
                            if downstream_triggers:
                                message += f"  📍 **影响下游触发器**: {', '.join(downstream_triggers)}\n"
                            if downstream_hosts:
                                message += f"  🔗 **下游主机**: {', '.join(downstream_hosts)}\n"
                    
                message += "\n"
        
        # 添加总结
        message += "## 📈 总结\n\n"
        # 统计实际数据：按主机和触发器分别统计
        unique_hosts = set()
        total_trigger_problems = 0
        for triggers in filtered_alerts.values():
            for trigger in triggers:
                unique_hosts.add(f"{trigger['hostname']}({trigger['ip']})")
                total_trigger_problems += 1
        
        message += f"🔍 本次检查发现 {len(filtered_alerts)} 种设备类型共 {len(unique_hosts)} 台主机存在 {total_trigger_problems} 个触发器告警\n"
        
        # 如果有告警变化，添加变化信息到总结
        if alert_changes and (alert_changes.get('new_alerts') or alert_changes.get('resolved_alerts') or alert_changes.get('changed_alerts')):
            change_summary = []
            if alert_changes.get('new_alerts'):
                change_summary.append(f"新增{len(alert_changes['new_alerts'])}个")
            if alert_changes.get('resolved_alerts'):
                change_summary.append(f"解决{len(alert_changes['resolved_alerts'])}个")
            if alert_changes.get('changed_alerts'):
                change_summary.append(f"变化{len(alert_changes['changed_alerts'])}个")
            
            if change_summary:
                message += f"🔄 本次检查: {', '.join(change_summary)}\n"
        
        message += "💡 请及时处理相关问题，确保系统稳定运行\n\n"
        message += "_消息由 Zabbix 监控系统自动发送_"
        
        return message
    
    def get_severity_emoji(self, severity):
        """根据严重程度返回对应的表情符号"""
        severity_map = {
            0: "✅",  # Not classified
            1: "🟢",  # Information  
            2: "🟡",  # Warning
            3: "🟠",  # Average
            4: "🔴",  # High
            5: "🟣"   # Disaster
        }
        return severity_map.get(severity, "⚪")
    
    def process_and_notify_alerts(self, alerts, alert_changes=None):
        """处理告警并发送通知"""
        try:
            # 分类告警
            classified_alerts = self.classify_alerts_by_type(alerts)
            
            # 格式化消息
            message = self.format_feishu_message(classified_alerts, alert_changes)
            
            # 发送飞书通知
            print("正在发送飞书通知...")
            self.webhook.send(message)
            print("飞书通知发送完成")
            
        except Exception as e:
            print(f"处理告警时出错: {e}")
    
    def start_monitoring(self):
        """启动定时监控"""
        print("🚀 Zabbix告警监控服务启动")
        print(f"⏰ 监控间隔: 每分钟检查一次")
        print(f"🕐 启动时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        print("-" * 50)
        
        # 立即执行一次检查
        print("执行初始检查...")
        # self.check_new_alerts()
        
        # 设置定时任务 - 每分钟执行一次
        schedule.every(5).seconds.do(self.check_new_alerts)
        
        # 保持程序运行
        try:
            while True:
                time.sleep(5) 
                schedule.run_pending()
        except KeyboardInterrupt:
            print("\n🛑 监控服务已停止")
        except Exception as e:
            print(f"监控服务运行出错: {e}")
        finally:
            if self.db_connection:
                self.db_connection.close()
                print("数据库连接已关闭")


def main():
    """主函数"""
    monitor = ZabbixAlertMonitor()
    monitor.start_monitoring()


if __name__ == "__main__":
    main()
